/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.st.service;

import java.math.BigDecimal;
import java.util.List;

import com.jeesite.modules.st.config.Constant;
import com.jeesite.modules.st.entity.*;
import com.jeesite.modules.st.utils.BillJudge;
import com.jeesite.modules.st.utils.BillUtil;
import com.jeesite.modules.st.utils.ErrorMsgException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.st.dao.StMaterialConvertBillDao;
import com.jeesite.modules.st.dao.StMaterialConvertBillDetailDao;

import javax.annotation.Resource;

/**
 * 物料转换单Service
 *
 * @author HOHD
 * @version 2021-03-10
 */
@Service
@Transactional(readOnly = true)
public class StMaterialConvertBillService extends CrudService<StMaterialConvertBillDao, StMaterialConvertBill> {

    @Autowired
    private StMaterialConvertBillDetailDao stMaterialConvertBillDetailDao;

    /**
     * 获取单条数据
     *
     * @param stMaterialConvertBill
     * @return
     */
    @Override
    public StMaterialConvertBill get(StMaterialConvertBill stMaterialConvertBill) {
        StMaterialConvertBill entity = super.get(stMaterialConvertBill);
        if (entity != null) {
            StMaterialConvertBillDetail stMaterialConvertBillDetail = new StMaterialConvertBillDetail(entity);
            stMaterialConvertBillDetail.setStatus(StMaterialConvertBillDetail.STATUS_NORMAL);
            entity.setStMaterialConvertBillDetailList(stMaterialConvertBillDetailDao.findList(stMaterialConvertBillDetail));
        }
        return entity;
    }

    /**
     * 查询分页数据
     *
     * @param stMaterialConvertBill 查询条件
     * @return
     */
    @Override
    public Page<StMaterialConvertBill> findPage(StMaterialConvertBill stMaterialConvertBill) {
        return super.findPage(stMaterialConvertBill);
    }

    @Resource
    BillUtil billUtil;
    @Autowired
    StMaterialRecordService stMaterialRecordService;
    @Autowired
    StProductRecordService stProductRecordService;

    /**
     * 保存数据（插入或更新）
     *
     * @param stMaterialConvertBill
     */
    @Override
    @Transactional(readOnly = false)
    public void save(StMaterialConvertBill stMaterialConvertBill) {
        Integer approveStatusPrime = stMaterialConvertBill.getApproveStatus();//save 肯定有一个
        Integer approveStatusDB;
        StMaterialConvertBill db = get(stMaterialConvertBill);
        if (stMaterialConvertBill.getIsNewRecord()) {
            approveStatusDB = -1;//默认值为null 不好
            String billNo = billUtil.billNo(BillUtil.BillType.materialConvertBill);
            stMaterialConvertBill.setBillNo(billNo);
        } else {
            approveStatusDB = db.getApproveStatus();
        }
        super.save(stMaterialConvertBill);
        // 保存 StMaterialConvertBill子表
        for (StMaterialConvertBillDetail stMaterialConvertBillDetail : stMaterialConvertBill.getStMaterialConvertBillDetailList()) {
            if (!StMaterialConvertBillDetail.STATUS_DELETE.equals(stMaterialConvertBillDetail.getStatus())) {
                stMaterialConvertBillDetail.setParentId(stMaterialConvertBill);
                if (stMaterialConvertBillDetail.getIsNewRecord()) {
                    stMaterialConvertBillDetailDao.insert(stMaterialConvertBillDetail);
                } else {

                    if (4 == approveStatusPrime && 2 == approveStatusDB) {
                        //审核
                        String convertMaterialCode = stMaterialConvertBillDetail.getConvertMaterialCode();//物料类型
                        String materialCode = stMaterialConvertBillDetail.getMaterialCode();
                        StMaterialRecord stMaterialRecord = new StMaterialRecord();
                        stMaterialRecord.setMaterialCode(convertMaterialCode);
                        StMaterialRecord convertMaterial = stMaterialRecordService.findMP(stMaterialRecord).get(0);
                        String materialType = convertMaterial.getMaterialType();
                        if (Constant.st_material_type.product.equals(materialType)) {
                            //直接抛异常
                            throw new ErrorMsgException("不能产品转产品");
                        } else if (Constant.st_material_type.wait_change.equals(materialType)) {
                            //怎么都不会错,还有一个原材料不能转

                        } else {
                            //产品转物料了
                            StProductRecord query = new StProductRecord();
                            query.setProductCode(materialCode);
                            StProductRecord productRecord = stProductRecordService.findList(query).get(0);
                            StMaterialRecord resMaterial = stMaterialRecordService.get(productRecord.getRawMaterialCode());//这里面存的是id
                            if (!convertMaterialCode.equals(resMaterial.getMaterialCode()))
                                throw new ErrorMsgException("要转换的物料不是半成品");
                        }
                        //生成仓库记录
                        String billNo = stMaterialConvertBill.getBillNo();
                        saveWarehouseInventory(BillUtil.BillType.materialConvertBill.getBillCode(), stMaterialConvertBillDetail, billNo);
                    }
                    if (4 == approveStatusDB && 2 == approveStatusPrime) {
                        removeWarehouseLog(stMaterialConvertBillDetail.getId());
                    }
                    stMaterialConvertBillDetailDao.update(stMaterialConvertBillDetail);
                }
            } else {
                stMaterialConvertBillDetailDao.delete(stMaterialConvertBillDetail);
            }
        }
    }

    // 新增和删除是成对的
    private void removeWarehouseLog(String id) {
        StWarehouseInventory stNull = new StWarehouseInventory();
        stNull.setPrimaryDetailId(id);
//            stNull.setBillNo(stInventoryBillDetail.getBillNo());
        List<StWarehouseInventory> list = stWarehouseInventoryService.findList(stNull);
        for (StWarehouseInventory warehouseInventory : list) {//调拨这种形式肯定就循环了
            stWarehouseInventoryService.delete(warehouseInventory);
        }
    }

    @Autowired
    StWarehouseInventoryService stWarehouseInventoryService;

    private void saveWarehouseInventory(Integer billType, StMaterialConvertBillDetail stMaterialConvertBillDetail, String billNo) {
        String id = stMaterialConvertBillDetail.getId();
        StWarehouseInventory warehouseInventory = new StWarehouseInventory();
        warehouseInventory.setBillNo(billNo);
        warehouseInventory.setBatchNumber(stMaterialConvertBillDetail.getBatchNumber());
        warehouseInventory.setPrimaryDetailId(id);
        Integer number = stMaterialConvertBillDetail.getNumber();
        if (null == number) number = 0;
        BigDecimal numberBD = new BigDecimal(number.doubleValue() + "");
        warehouseInventory.setNumber(numberBD);
        warehouseInventory.setMaterialCode(stMaterialConvertBillDetail.getMaterialCode());

        warehouseInventory.setProductDate(stMaterialConvertBillDetail.getProductDate());
        warehouseInventory.setSavedType(stMaterialConvertBillDetail.getSavedType());
        warehouseInventory.setPassDate(stMaterialConvertBillDetail.getPassDate());

        warehouseInventory.setBillCategory(billType);//种类

        //调拨单
        warehouseInventory.setInOrOut(Constant.in_or_out.out);//出库
        String allotOutWarehouse = stMaterialConvertBillDetail.getOutWarehouse();
        warehouseInventory.setWarehouse(allotOutWarehouse);
        warehouseInventory.setNumber(numberBD);
        //
        StWarehouseInventory warehouseInventoryIn = new StWarehouseInventory();
        BeanUtils.copyProperties(warehouseInventory, warehouseInventoryIn);
        warehouseInventoryIn.setInOrOut(Constant.in_or_out.in);
        warehouseInventoryIn.setWarehouse(stMaterialConvertBillDetail.getInWarehouse());
        warehouseInventoryIn.setMaterialCode(stMaterialConvertBillDetail.getConvertMaterialCode());
        stWarehouseInventoryService.save(warehouseInventoryIn);
        stWarehouseInventoryService.save(warehouseInventory);
    }

    /**
     * 更新状态
     *
     * @param stMaterialConvertBill
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(StMaterialConvertBill stMaterialConvertBill) {
        super.updateStatus(stMaterialConvertBill);
    }

    /**
     * 删除数据
     *
     * @param stMaterialConvertBill
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(StMaterialConvertBill stMaterialConvertBill) {
        super.delete(stMaterialConvertBill);
        StMaterialConvertBillDetail stMaterialConvertBillDetail = new StMaterialConvertBillDetail();
        stMaterialConvertBillDetail.setParentId(stMaterialConvertBill);
        stMaterialConvertBillDetailDao.deleteByEntity(stMaterialConvertBillDetail);
    }

}